package com.geek.javase.ch17.work.tcpwork.tcp5;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.SocketException;

/*
 *@Date 2025/11/4
 *@Author wangpeng
 *@Description
 *读写撤离
 */
public class ReadThread implements Runnable{
    private Socket socket;
    public ReadThread(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        try(
                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        ){
            String str = null;
            while((str= br.readLine())!=null){
                if(str.equals("exit")){
                    System.out.println(socket.getRemoteSocketAddress()+"已下线！");
                    break;
                }else{
                    System.out.println(socket.getRemoteSocketAddress()+"说："+str);
                }
            }
        }catch (SocketException e){
            System.out.println("拜拜！");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
